package protocol.work.connection;

import java.lang.reflect.Constructor;

import protocol.common.entity.HttpConnConfig;
import protocol.common.entity.HttpParametersConfig;
import protocol.common.entity.ParametersType;
import protocol.work.connection.http.HttpWorkConnection;
import protocol.work.connection.http.IConnectionWork;


public class ConnectionFactory{
	
	public static ConnectionManager createQueryConnection(HttpConnConfig connConfig){
		return ConnectionFactory.createQueryConnection(new ConnectionManager(),connConfig);
	}
	
	public static ConnectionManager createQueryConnection(ConnectionManager connManager,HttpConnConfig connConfig){
		HttpParametersConfig parametersConfig = connConfig.getParametersConfig(ParametersType.SEND);
		try {
			//创建发送线程
			int forCount = parametersConfig.getWorkCount();
			for(int i = 0;i < forCount;i++){
				IConnectionWork connectionWork = ConnectionFactory.createSendWorkHandle(connConfig);
				HttpWorkConnection httpWorkConnection = new HttpWorkConnection(connConfig,connectionWork);
				connManager.addConnection(connConfig.getChannle()+"-Send-"+(i+1),httpWorkConnection);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return connManager;
	}
	
	@SuppressWarnings("unchecked")
	public static IConnectionWork createSendWorkHandle(HttpConnConfig connConfig) throws Exception{
		Class classType =  Class.forName(connConfig.getParametersConfig(ParametersType.SEND).getParametersClass());  
		Constructor<IConnectionWork> con = classType.getConstructor(HttpConnConfig.class);  
        return con.newInstance(connConfig);
	}
	
}
